function withTimeout(promiseFn, timeout = 5000, err = "Operation timed out") {
  return function (...args) {
    return new Promise((resolve, reject) => {
      const timeoutId = setTimeout(() => {
        reject(new Error(`${promiseFn.name} ERROR: ${err}`));
      }, timeout);

      promiseFn(...args)
        .then((result) => {
          clearTimeout(timeoutId);
          resolve(result);
        })
        .catch((error) => {
          clearTimeout(timeoutId);
          reject(error);
        });
    });
  };
}

export function isPC() {
  let flag = navigator.platform.match(/(Win|Mac)/i);
  console.log("isPC", !!flag);
  return !!flag;
}
export function isZxcxAPP() {
  let u = navigator.userAgent;
  return u.indexOf("zxcxapp") > -1;
}
export function isIOS() {
  let u = navigator.userAgent;
  return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
}
function isIOSwithPad() {
  let flag = false;
  if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
    //  'iOS'
    flag = true;
  } else if (/Macintosh/i.test(navigator.userAgent)) {
    //  'macOS'
    flag = true;
  }
  return flag;
}
export function isAndroid() {
  let u = navigator.userAgent;
  return u.indexOf("Android") > -1 || u.indexOf("Adr") > -1;
}

export function isWechat() {
  const ua = navigator.userAgent.toLowerCase();
  return ua.includes("micromessenger");
}
/**
 * 调用分享
 * @param {Object} str
 * str:{desc:分享描述,title: 分享标题,imgUrl: 分享小图,link:分享链接}
 *
 */
export function zxcxShareAction(str) {
  if (isPC()) {
    console.error("platform error:", navigator.userAgent.platform);
    return;
  }
  if (isIOS()) {
    window.webkit.messageHandlers.zxcxShareAction.postMessage(str);
  } else if (isAndroid()) {
    window.android.zxcxShareAction(JSON.stringify(str));
  }
}

/**
 * 获取用户定位
 * @param {Function} callback
 * callback: (res) => { // TODO: JSON.parse(res)}
 * @returns
 */
export function zxcxStartLocation() {
  return new Promise((resolve, reject) => {
    if (isPC()) {
      reject("platform error");
    }
    window["getLocationInfo"] = (infoStr) => {
      const location = JSON.parse(infoStr);
      if (location) {
        resolve(location);
      } else {
        reject("NOT_LOGIN");
      }
      delete window["getLocationInfo"];
    };

    if (isIOS()) {
      window.webkit.messageHandlers.zxcxStartLocation.postMessage(
        "zxcxStartLocation"
      );
    } else if (isAndroid()) {
      window.android.zxcxStartLocation();
    }
  });
}
/**
 * 扫一扫
 * @param {String} zxcxInputValue
 */
export function zxcxScanInputValue(zxcxInputValue = "source=zxcxmall") {
  if (isPC()) {
    console.error("platform error:", navigator.userAgent.platform);
    return;
  }
  let str = {
    zxcxInputValue,
  };
  if (isIOS()) {
    window.webkit.messageHandlers.zxcxScanInputValue.postMessage(str);
  } else if (isAndroid()) {
    window.android.zxcxScanInputValue(JSON.stringify(str));
  }
}

/**
 * 控制隐藏显示TitleBar（右上角刷新或者分享icon)
 * @param {Number} isShow
 * 0-显示1-隐藏
 * @returns
 */
export function zxcxRightTitleBarHideSwitch(isShow) {
  if (isPC()) {
    console.error("platform error:", navigator.userAgent.platform);
    return;
  }
  if (isIOS()) {
    window.webkit.messageHandlers.zxcxRightTitleBarHideSwitch.postMessage(
      isShow
    );
  } else if (isAndroid()) {
    window.android.zxcxRightTitleBarHideSwitch(isShow);
  }
}
/**
 * 农商行ＳＤＫ
 * @param {String} url
 * @returns
 */
export function zxcxZjrcActivateAction(url) {
  if (isPC()) {
    console.error("platform error:", navigator.userAgent.platform);
    return;
  }
  if (isIOS()) {
    window.webkit.messageHandlers.zxcxZjrcActivateAction.postMessage(url);
  } else if (isAndroid()) {
    window.android.zxcxZjrcActivateAction(url);
  }
}

/**
 * 原生判断URL
 * @param {String} url
 * @param {Object} param
 * 扫一扫：zjfk://?page=scan
 * 商城客服：zjfk://?page=chat
 * 原生商城：zjfk://?page=shop
 * 原生商城：zxcxmall://?index
 * 跳转原生商城商品详情：zxcxmall://?id=1690
 * 跳转原生商城商品详情：zxcxmall://?code=1690
 * 跳转原生商城优惠券活动页面：zxcxmallcoupon://?couponId=1690
 * 跳转微信小程序: wxxcx://?userName={小程序原始ID}&path={小程序path}
 */
export function locationFunc(url, param) {
  let href = url;
  if (param) {
    Object.keys(param).forEach((item, index) => {
      href += `${index === 0 && url.indexOf("?") < 0 ? "?" : "&"}${item} = ${
        param[item]
      }`;
    });
  }
  window.location.href = href;
}
/**
 * 跳转原生(已弃用，iOS端不支持)
 * @param {Object} params
 *
 * @param {Number} params.contentType -0:跳转app首页-推荐-发现页 -1 (新闻详情:新闻id) -2 (服务类型) -3 (专题类型:专题id)
 * -4 (商品详情:商品id,id=0，跳指尖商城首页 ) -5(外链: 携带参数外链link ) -6(私信) -7 (话题详情:话题id ) -8 个人中心(id:用户ID) -9 看电视(link) -10 听广播(link)
 * @param {String} params.contentTypeId 携带的id
 * @param {Number} params.appletsSign 是否是小程序 0:(非小程序) -1(小程字) -2 (浙里办)
 * @param {String} params.promotionld 商城活动id
 * @param {String} params.promotionType 商城活动类型
 * @param {String} params.skuld 商城商品SKUID
 * @param {String} params.link 外链
 */
export function zxcxPushToNotiActionV1(params) {
  let str = params;
  let u = navigator.userAgent;
  let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
  if (isIOS) {
    window.webkit.messageHandlers.zxcxPushToNotiAction.postMessage(str);
  } else if (isAndroid) {
    window.android.zxcxPushToNotiAction(JSON.stringify(str));
  }
}

/**
 * 跳转原生
 * @param {Object} params
 * @param {Number} params.contentType  - 0:跳转app首页-推荐-发现页
 * 1 (新闻详情:新闻id)
 * 2 (应用)
 * 3 (专题)
 * 4 (商品详情、商城首页 ) 5(外链 ) 6(私信) 7 (话题 ) 8 个人中心 9 看电视 10 听广播
 * 11 抢券 12 帖子详情
 * @param {String} params.contentTypeId - 携带的id或者链接
 * @param {Object} params.contentTypeData - 携带数据对象
 * contentType=2时，{ serviceId:string,serviceName:string,url:string,
 * needRealNam:number, //1需要实名，2不需要实名
 * appletSign:number, //0:h5服务 1:微信小程序 2:这里办服务 3:抢券 appId:string, path:string }
 *  contentType=4时，{ goodsId:string,promotionId:string,skuId:string,promotionType:number }
 */
export function zxcxPushToNotiAction(params) {
  if (isPC()) {
    console.error("PLATFORM_ERROR");
    return;
  }
  let str = JSON.stringify(params);
  if (isIOS()) {
    window.webkit.messageHandlers.zxcxPushToNotiAction.postMessage(str);
  } else if (isAndroid()) {
    window.android.zxcxPushToNotiAction(str);
  }
}

/**
 * 控制标题右侧按钮
 * @param {Object} params
 * @param {String} params.hideTitleBar 控制导航栏 - 0:显示，- 1：隐藏
 * @param {String} params.hideTitleBarIcon 控制导航栏右侧图标,0：刷新，1：分享，2：不显示
 */
export function zxcxActionHideTitleBar(params) {
  if (isPC()) {
    console.error("platform error:", navigator.userAgent.platform);
    return;
  }
  if (isIOS()) {
    window.webkit.messageHandlers.zxcxActionHideTitleBar.postMessage(params);
  } else if (isAndroid()) {
    window.android.zxcxActionHideTitleBar(JSON.stringify(params));
  }
}

/**
 * 微信支付
 * @param {String} jsonStr JSON 字符串
 * @param {Function} callback 付款跳转返回后回调方法
 * @returns
 */
export function zxcxWXPay(jsonStr) {
  return new Promise((resolve, reject) => {
    if (isPC()) {
      reject("PLATFORM_ERROR");
    }
    window["zxcxWXPayResultCallBack"] = (payRes) => {
      console.log("zxcxWXPayResultCallBack", payRes);
      resolve(payRes);
      delete window["zxcxWXPayResultCallBack"];
    };
    if (isIOS()) {
      window.webkit.messageHandlers.zxcxWXPay.postMessage(jsonStr);
    } else if (isAndroid()) {
      window.android.zxcxWXPay(jsonStr);
    }
  });
}
export const zxcxWXPayWithTimeout = withTimeout(
  zxcxWXPay,
  5000,
  "拉起微信超时"
);
/**
 * 获取用户信息OpenId(对外)
 * @returns {Promise<{openId: string, nickName: string, avatar: string, authSign: boolean}>}
 */
export function getUserInfo() {
  return new Promise((resolve, reject) => {
    if (isPC()) {
      reject("ERROR_CODE.PLATFORM_ERROR");
    }
    if (isIOS()) {
      window.webkit.messageHandlers.zxcxGetOpenId.postMessage(
        "zxcxGetOpenIdiOS"
      );
      window.zxcxGetOpenIdiOS = (userinfoStr) => {
        const userinfo = JSON.parse(userinfoStr);
        if (userinfo && userinfo.openId) {
          resolve(userinfo);
        } else {
          reject("NOT_LOGIN");
        }
        delete window["zxcxGetOpenIdiOS"];
      };
    } else if (isAndroid()) {
      if (window.android.zxcxGetOpenId) {
        const userinfoStr = window.android.zxcxGetOpenId();
        const userinfo = JSON.parse(userinfoStr);
        if (userinfo && userinfo.openId) {
          resolve(userinfo);
        } else {
          reject("NOT_LOGIN");
        }
      } else {
        const url = window.location.href;
        let start = url.indexOf("token=");
        const token = url.substring(start + 6);
        console.log(
          "isAndroid,!!window.android.zxcxGetUserInfo",
          window.location.href,
          token
        );
        if (!token) {
          reject("NOT_LOGIN");
        } else {
          fetch(
            `https://openapi.cxepsp.com/api/v1/user/token?token=${token}`
          ).then((res) => {
            if (res.ok) {
              res.json().then((data) => {
                if (data.code == 200) {
                  resolve(data.result);
                } else {
                  reject(data.msg);
                }
              });
            } else {
              reject("FAIL_IN_fetch_USER_INFO");
            }
          });
        }
      }
    }
  });
}
/**
 * 获取APP登录用户userId
 *@returns { {userId: string,avatar: string,nickName: string,authSign: boolean} }
 */
export function zxcxGetUserInfo() {
  return new Promise((resolve, reject) => {
    if (isPC()) {
      reject("platform error");
    }
    if (isIOS()) {
      window.webkit.messageHandlers.zxcxGetUserInfo.postMessage(
        "zxcxGetUserInfoiOS"
      );
      window.zxcxGetUserInfoiOS = (info) => {
        resolve(info);
        delete window["zxcxGetUserInfoiOS"];
      };
    } else if (isAndroid()) {
      if (window.android.zxcxGetUserInfo) {
        resolve(window.android.zxcxGetUserInfo());
      } else {
        const url = window.location.href;
        let start = url.indexOf("token=");
        const token = url.substring(start + 6);
        console.log(
          "isAndroid,!!window.android.zxcxGetUserInfo",
          window.location.href,
          token
        );
        if (!token) {
          reject("NOT_LOGIN");
        } else {
          fetch(
            `https://openapi.cxepsp.com/api/v1/user/token?token=${token}`
          ).then((res) => {
            if (res.ok) {
              res.json().then((data) => {
                if (data.code == 200) {
                  resolve(JSON.stringify(data.result));
                } else {
                  reject(data.msg);
                }
              });
            }
          });
        }
      }
    }
  });
}
/**
 * H5获取APP版本和设备信息
 *@returns { {deviceToken: String, phoneType: String }}
 */
export function zxcxGetDeviceInfo() {
  return new Promise((resolve, reject) => {
    if (isPC()) {
      reject("platform error");
    }
    if (isIOS()) {
      window.webkit.messageHandlers.zxcxGetDeviceInfo.postMessage(
        "zxcxGetDeviceInfoiOS"
      );
      window.zxcxGetDeviceInfoiOS = (info) => {
        resolve(info);
        delete window["zxcxGetDeviceInfoiOS"];
      };
    } else if (isAndroid()) {
      resolve(window.android.zxcxGetDeviceInfo());
    }
  });
}

/**
 * 获取版本信息
 * @returns {Promise<{versionName: string, isNewestVersion: boolean}>}
 */
export function getVersion() {
  return new Promise((resolve, reject) => {
    if (isPC()) {
      reject("platform error");
    }
    if (isIOS()) {
      window.webkit.messageHandlers.zxcxGetVersionInfo.postMessage(
        "zxcxGetVersionInfoiOS"
      );
      window.zxcxGetVersionInfoiOS = (info) => {
        resolve(info);
        delete window["zxcxGetVersionInfoiOS"];
      };
    } else if (isAndroid()) {
      resolve(window.android.zxcxGetVersionInfo());
    }
  });
}

/**
 * App关闭H5页面
 * @returns {void}
 */
export function zxcxH5Close() {
  if (isPC()) {
    console.error(ERROR_CODE.PLATFORM_ERROR);
    return;
  }
  if (isIOS()) {
    window.webkit.messageHandlers.zxcxCloseH5.postMessage("zxcxH5Close");
  } else if (isAndroid()) {
    window.android.zxcxH5Close();
  }
}
